Initialize a Dictionary with Empty List in Python

您所在的位置:网站首页 std list empty Initialize a Dictionary with Empty List in Python

Initialize a Dictionary with Empty List in Python

2023-04-17 10:52| 来源: 网络整理| 查看: 265

This tutorial will discuss about unique ways to initialize a dictionary with empty list in Python.

Table Of Contents

Using Dictionary Comprehension Using fromkeys() method Summary Using Dictionary Comprehension

Dictionary in Python stores the data as a key value pairs. Now suppose you want to store an empty list as a value for each key in the dictionar.

So, we can do that using two ways, first one is a dictionary comprehension. Where, we will iterate over the sequence of keys and for each key we will assign the value as empty list in the dictionary comprehension. It will return a dictionary containing keys from the list but each value will be the empty list.

Let’s see the complete example,

Advertisements listOfKeys = ['Ritika', 'Atharv', 'Smriti', 'Mathew', 'John'] # Create a dictionary with empty list as values dictObj = {key: [] for key in listOfKeys} print(dictObj)

Output

{'Ritika': [], 'Atharv': [], 'Smriti': [], 'Mathew': [], 'John': []} Using fromkeys() method

To initialise a dictionary with keys and an empty list as the default value, we can use the fromkeys() method from the dictionary. We will pass the list of keys as first argument and an empty list as the second argument in the fromkeys() method.

Read More  How to plot a correlation matrix in pandas?

It will initialise, and return a dictionary object, where the items from the list keys will be the keys in the key-value pairs, and each key will have the empty list as default value.

Let’s see the complete example,

listOfKeys = ['Ritika', 'Atharv', 'Smriti', 'Mathew', 'John'] # Create a dictionary with empty list as values dictObj = dict.fromkeys(listOfKeys, []) print(dictObj)

Output

Read More  How to Initialize a Dictionary with List in Python {'Ritika': [], 'Atharv': [], 'Smriti': [], 'Mathew': [], 'John': []} Summary

We learned about two different ways to initialise a dictionary with an empty list in Python.

Related posts: Python : 6 Different ways to create Dictionaries Create a Dictionary from two Lists in Python Create Python Dictionary in One Line Create a Python Dictionary with values Create Dictionary With Predefined Keys in Python Create Dictionary Iteratively in Python Create New Dictionary from Existing Dictionary in Python How to Initialize empty Dictionary in Python? How to Initialize a Dictionary With Keys in Python How to Initialize a Dictionary with 0 in Python?


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3